<template>
	<view class="pageview">
		<firstConnect
			v-if="isFirst"
			:device-type="deviceType"
			:deviceStatus="deviceStatus"
			@startUse="startUse"
			@retry="retry"
		></firstConnect>
		<template v-else>
			<view class="toptip flex align-center justify-between" v-if="!connectedDevice || deviceStatus == 3">
				<text>{{ blueState ? "当前设备未连接，请连接设备" : "需要开启蓝牙，连接设备" }}</text>
				<view class="btn flex align-center" @click="devicesDiscovery" v-if="blueState">
					<u-loading-icon
						color="#fff"
						:show="deviceStatus == 0 || deviceStatus == 1 || reconnectCount > 0"
					></u-loading-icon>
					<text>去连接</text>
				</view>
			</view>
			<template v-if="deviceStatus == 2">
				<view class="toptip flex align-center justify-between">
					<text v-if="contactedStatus != '06'">
						{{
							contactedStatus == "01"
								? "导联未连接，请检测佩戴"
								: contactedStatus == "02"
								? "设备连接异常"
								: ""
						}}
					</text>
					<view class="flex align-center" v-else>
						<text class="u-margin-right-10">监测时长</text>
						<smh-timer ref="timer" @timing="timing" :auto="false"></smh-timer>
					</view>
					<text v-if="connectedDevice && connectedDevice.localName">
						{{ connectedDevice.localName.slice(10) }}
					</text>
				</view>
			</template>
			<!-- <view class="toolbar flex align-center justify-between">
				<view class="flex align-center" v-if="false">
					<text class="u-margin-right-10">监测时长</text>
					<smh-timer ref="timer" @timing="timing" :auto="false"></smh-timer>
				</view>
				<view></view>
				<view v-if="connectedDevice && connectedDevice.localName">
					{{ connectedDevice.localName.slice(10) }}
				</view>
			</view> -->
			<div class="flex justify-between align-center u-p-20" style="background: #fff">
				<div class="blueState u-flex u-flex-column">
					<image src="/static/device/bluetooth.png" mode="widthFix" v-if="contactedStatus != 06"></image>
					<image src="/static/device/bluetooth_cur.png" mode="widthFix" v-else></image>
					<span class="name" :class="{ active: contactedStatus == '06' }">
						{{ contactedStatus == "06" ? "已连接" : "未连接" }}
					</span>
				</div>
				<div class="electricityState">
					<div class="battery-indicator u-flex u-flex-column">
						<div class="battery-container" :style="{ '--battery-level': batteryValue + '%' }">
							<div class="battery-level" :class="{ 'low-battery': isLowBattery }"></div>
							<div class="battery-head"></div>
						</div>
						<span
							class="battery-percent"
							v-if="batteryValue != null"
							:class="{ 'low-battery': isLowBattery }"
						>
							{{ batteryValue }}%
						</span>
					</div>
				</div>
			</div>
		</template>
		<view
			class="charts"
			:class="{
				hideCanvas: isFirst
			}"
		>
			<view class="charts-box linecharts">
				<!-- <qiun-data-charts type="line" :opts="opts1" :chartData="chartData" canvas2d :pixelRatio="2" /> -->
				<Lt-ECG :ecgArr="ecgArr"></Lt-ECG>
				<view class="u-m-t-20 u-flex justify-between u-p-l-20 u-p-r-20 align-center" style="font-size: 24rpx">
					<view class="u-flex align-center">
						<text>增益：</text>
						<uni-data-select style="width: 180rpx" v-model="gain" :localdata="gainList"></uni-data-select>
						<!-- <text>10mm/mv</text> -->
					</view>
					<text>走速：25mm/s</text>
					<!-- <text>导联Ⅱ；</text> -->
					<text>采样频率：1000Hz</text>
				</view>
				<view class="u-m-t-20 u-flex justify-between u-p-l-20 u-p-r-20 align-center" style="font-size: 24rpx">
					<view class="u-flex align-center">
						<text>实时数据校准：</text>
						<uni-data-select
							style="width: 180rpx"
							@change="changeMode"
							v-model="waveMode"
							:localdata="modeList"
						></uni-data-select>
					</view>
					<view class="u-flex align-center">
						<text>存储数据校准：</text>
						<uni-data-select
							style="width: 180rpx"
							@change="changeSaveMode"
							v-model="saveWaveMode"
							:localdata="modeList"
						></uni-data-select>
					</view>
					<!-- <text>走速：25mm/s</text> -->
					<!-- <text>导联Ⅱ；</text> -->
					<!-- <text>采样频率：1000Hz</text> -->
				</view>
			</view>
			<!-- <view class="charts-box linechartsCopy">
				<qiun-data-charts type="line" :opts="opts2" :chartData="chartData" canvas2d />
			</view> -->
			<!-- 开始标志 -->
			<!-- <view class="start-icon">
				<view class="line1"></view>
				<view class="line2"></view>
				<view class="line3"></view>
			</view> -->
			<view class="bpm flex align-center">
				<!-- <text class="num u-margin-right-10">{{ bpmData || '--' }}</text> -->
				<view class="num u-margin-right-10">
					<u-count-to
						ref="uCountTo"
						bold
						:duration="500"
						color="#1c1b21"
						:fontSize="60"
						:endVal="bpmData"
						autoplay
					></u-count-to>
				</view>
				<text>bpm</text>
			</view>
		</view>

		<u-popup :closeOnClickOverlay="false" :closeable="true" :show="show" mode="center" :round="20" @close="close">
			<view class="popup" @touchmove.stop.prevent>
				<view class="popup-hd">选择设备</view>
				<scroll-view class="popup-bd" scroll-y="true">
					<view
						class="device"
						@tap="connectToDevice(index)"
						v-for="(item, index) in devicesDiscovered"
						:key="index"
					>
						<view>
							<view class="name">{{ item.name }}</view>
							<view>{{ item.deviceId }}</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<view class="u-flex" style="padding: 30rpx" v-if="deviceStatus == 2 && !isFirst">
			<view class="u-flex-sub">
				<u-button
					shape="circle"
					size="small"
					type="primary"
					text="开始离线测量"
					@click="handleComfirm('start')"
				></u-button>
			</view>
			<view class="u-flex-sub u-m-l-10">
				<u-button
					:disabled="deviceStatus != 2"
					shape="circle"
					type="success"
					size="small"
					text="结束离线测量"
					@click="handleComfirm('stop')"
				></u-button>
			</view>

			<view class="u-flex-sub u-m-l-10" v-if="false">
				<u-button
					:disabled="deviceStatus != 2"
					shape="circle"
					type="success"
					size="small"
					text="同步时间"
					@click="asyncTime()"
				></u-button>
			</view>

			<!-- <view class="u-m-l-10">
				<u-button shape="circle" type="success" size="small" text="滤波数据" @click="setMode(3)"></u-button>
			</view>
			<view class="u-m-l-10">
				<u-button shape="circle" type="warning" size="small" text="原始数据" @click="setMode(1)"></u-button>
			</view> -->
		</view>

		<view class="footerbar u-flex" v-if="!isFirst">
			<view class="u-flex-sub">
				<u-button shape="circle" type="primary" text="更换设备" @click="resetdevicesDiscovery"></u-button>
			</view>
			<view class="u-flex-sub u-m-l-10">
				<u-button
					:disabled="deviceStatus != 2"
					shape="circle"
					type="success"
					text="清除历史数据"
					@click="handleComfirm('clear')"
				></u-button>
			</view>
			<view class="u-flex-sub u-m-l-10">
				<navigator target="miniProgram" open-type="exit">
					<u-button shape="circle" type="error">退出小程序</u-button>
				</navigator>
			</view>
		</view>
		<!-- 确认 -->
		<u-modal
			:show="confirmShow"
			title="确认提示"
			:content="content"
			@confirm="confirm"
			@cancel="confirmShow = false"
			ref="uModal"
			:showCancelButton="true"
		></u-modal>
		<view class="footerbar" v-if="isFirst && deviceStatus != 2 && deviceStatus != 3">
			<navigator target="miniProgram" open-type="exit">
				<u-button type="error">退出小程序</u-button>
			</navigator>
		</view>
	</view>
</template>

<script>
import { ab2str, formatNum, formatSecond, chunk } from "@/utils/util";
const ER2Protocol = require("@/utils/ble_devices/er2");
const ERBuilder = {
	// 注意这里的this是实例化后的ER2对象，而不是page
	notifyServiceId: [
		"0000180D-0000-1000-8000-00805F9B34FB",
		"0000322D-0000-1000-8000-00805F9B34FB",
		"0000180F-0000-1000-8000-00805F9B34FB"
	],
	deviceFoundFilter: (item) => /(ZHS|KNX)/.test(item.name),
	connectionStateChange: function (res) {
		console.log("ER连接状态改变", res);
		this.connectionState = res.connected;
	},
	characteristicValueChange: function (res) {
		if (res.value) {
			// 开始解析数据
			if (res.value !== this.oldCallbackData) {
				//可能会有重复的包
				this.oldCallbackData = res.value;
				console.log("上报了数据");
				// 而且微信返回的value是ArrayBuffer，所以同样要先转换成str
				if (res.serviceId == "0000322D-0000-1000-8000-00805F9B34FB") {
					this.parseData(ab2str(res.value));
				} else if (res.serviceId == "0000180D-0000-1000-8000-00805F9B34FB") {
					//心率
					// console.log('ER监听数据', res);
					this.parseBPMData(ab2str(res.value));
				} else if (res.serviceId == "0000180F-0000-1000-8000-00805F9B34FB") {
					//电量
					// console.log("ER电量监听数据", res, ab2str(res.value));
					this.parseBATTERYData(ab2str(res.value));
				}
			}
		}
	}
};
const ER = new ER2Protocol(ERBuilder);
let foundTimer = null,
	saveTimer = null;
var LineCIds = null;
let categories = [];

import firstConnect from "./components/firstConnect";
import O2Chart from "./components/O2Chart";
import mixin from "./mixin.js";
import { mapState } from "vuex";
let packNum = 0,
	batchId = "";
export default {
	mixins: [mixin],
	data() {
		return {
			isConnected: false, // 是否连接设备
			devicesDiscovered: [], // 设备列表
			connectedDevice: null, // 当前连接设备
			deviceType: "ER",
			deviceTypeId: "ER",
			isFirst: true,
			deviceStatus: -1,
			deviceData: [],
			blueState: false, //蓝牙状态
			chartData: {
				categories: [],
				series: [
					{
						name: "心电图",
						data: []
					}
				]
			},
			opts1: {
				rotate: false,
				rotateLock: false,
				color: ["#fd0e13"],
				padding: [10, 5, 0, 0],
				legend: {
					show: false
				},
				dataLabel: false,
				dataPointShape: false,
				animation: false,
				update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
				duration: 0,
				xAxis: {
					disabled: false, //不显示x轴
					disableGrid: false,
					boundaryGap: "justify",
					type: "grid",
					gridColor: "#36b743",
					// gridType: 'dash',
					// dashLength: 0.5,
					labelCount: 31,
					gridEval: 100,
					data: [
						{
							min: 0,
							max: 3000
						}
					],
					// splitNumber: 31,
					fontSize: 6,
					rotateLabel: true,
					marginTop: 5,
					axisLine: false,
					format: "mictimexAxisformat"
				},
				yAxis: {
					disabled: false, //不显示y轴
					// disableGrid: false,
					gridType: "solid",
					dashLength: 0.5,
					gridColor: "#36b743",
					gridEval: 0.1,
					splitNumber: 20,
					data: [
						{
							axisLine: false,
							min: -1,
							max: 1,
							tofix: 1,
							fontSize: 10,
							fontColor: "#050006",
							format: "timeyAxisformat"
						}
					]
				},
				extra: {
					tooltip: {
						showBox: false,
						splitLine: false
					},
					line: {
						activeType: "none",
						width: 2
					}
				}
			},
			ecglist: [],
			oldecglist: [],
			bpmData: null,
			contactedStatus: "01", //导联未连接
			show: false,
			batteryValue: null,
			ecgArr: [],
			emptyWaveCount: 0,
			gain: 1,
			gainList: [
				{ value: 2, text: "5mm/mv" },
				{ value: 1, text: "10mm/mv" },
				{ value: 0.5, text: "20mm/mv" }
			],
			deviceMac: "",
			reconnectCount: 0, // 新增重连计数
			maxReconnect: 5, // 最大重连次数
			modeList: [
				{
					value: 0,
					text: "原始数据"
				},
				{
					value: 1,
					text: "二分频"
				},
				{
					value: 2,
					text: "四分频"
				},
				{
					value: 3,
					text: "高通"
				},
				{
					value: 4,
					text: "低通"
				}
			],
			waveMode: 4, //实时默认低通
			saveWaveMode: 2, //存储默认四分频
			confirmType: "stop", //确认弹出框类型
			confirmShow: false
		};
	},
	computed: {
		...mapState(["userInfo", "curAccount", "doctorId"]),
		isLowBattery() {
			return parseFloat(this.batteryValue) <= 20;
		},
		content() {
			if (this.confirmType == "start") {
				let info = this.modeList.find((item) => item.value == this.saveWaveMode);
				return "当前存储数据模式为【" + info.text + "】，开始测量后，马达会震动两次";
			}
			return this.confirmType == "stop" ? "你确定要结束离线测量吗？" : "你确定要清除历史数据吗？";
		}
	},
	components: {
		firstConnect
	},
	onShareAppMessage(res) {
		return {
			title: "心电监测",
			path: "/pages/device/erdevice?deviceType=ER", // 分享路径，可根据需要调整参数
			imageUrl: "https://res.knxchip.com/device/ER2.jpg"
		};
	},
	onLoad(optioin) {
		ER.contactedStatus = ""; //把导联状态置空
		ER.adapterState = false; //蓝牙状态
		ER.init();
		this.deviceType = optioin.deviceType;
		this.isFirst = true;
		const appInstance = getApp();
		appInstance.watch(this, ER, {
			//蓝牙配置状态
			adapterState: function (newVal) {
				console.log("adapterState", newVal);
				if (newVal && !this.blueState) {
					this.blueState = true; //设置蓝牙初始化成功了
					this.deviceStatus = -1;
					if (this.isFirst) {
						this.devicesDiscovery();
					}
				}
			},
			foundDevices: function (newVal) {
				if (
					JSON.stringify(newVal) != JSON.stringify(this.devicesDiscovered) &&
					newVal.length > 0 &&
					!this.isConnected
				) {
					this.devicesDiscovered = [...new Map(newVal.map((item) => [item.deviceId, item])).values()];
					console.log("this.devicesDiscovered", this.devicesDiscovered);
					let index = -1;
					if (this.deviceMac) {
						index = this.devicesDiscovered.findIndex((item) => item.deviceId == this.deviceMac);
					} else {
						this.show = true;
						// index = this.devicesDiscovered.findIndex(item => /(ZHS)/.test(item.name));
					}
					if (index > -1) {
						this.deviceStatus = 1;
						this.connectToDevice(index);
					}
				}
			},
			connectedDevice: function (newVal) {
				console.log("connectedDevice", newVal);
				this.isConnected = !!newVal;
				this.connectedDevice = newVal;
				this.deviceMac = this.isConnected ? this.connectedDevice.deviceId : "";
				if (this.isConnected) {
					this.deviceStatus = 2;
					ER.connectionState = true;
				}
			},
			bpm: function (newVal) {
				this.bpmData = newVal < 30 ? 30 : newVal > 250 ? 250 : newVal;
			},
			battery: function (newVal) {
				this.batteryValue = newVal;
				if (newVal) {
					// this.send_testtwo(
					// 	JSON.stringify({
					// 		oprDocterID: this.doctorId,
					// 		mac: this.deviceMac,
					// 		type: "Electric",
					// 		value: this.batteryValue
					// 	})
					// );
				}
			},
			connectionState: function (newVal) {
				this.deviceStatus = newVal ? 2 : 3;
				console.log("设备断开了，到这里了吗");
				//表示链接断开了
				if (this.deviceStatus == 3) {
					this.batteryValue = null;
					// ====== 新增重连逻辑 ======
					this.reconnectToDevice();
				} else {
					this.reconnectCount = 0; // 连接成功重置计数
				}
			},
			//导联连接状态
			contactedStatus: function (newVal, oldVal) {
				if (newVal != this.contactedStatus) {
					this.contactedStatus = newVal;
					if (this.contactedStatus != "06") {
						this.clear();
					} else {
						ER.oldtimestamp = 0;
						this.$nextTick(() => {
							this.reset();
						});
					}
				}
			}
		});

		//x轴数据

		let data = [];
		categories = [];
		for (var i = 0; i < 3001; i++) {
			categories.push(i);
			data.push(0);
		}

		this.oldecglist = [...data];
		this.ecglist = [];
		this.ecgArr = [];
		this.chartData = JSON.parse(
			JSON.stringify({
				categories,
				series: [
					{
						name: "心电图",
						data: data
					}
				]
			})
		);
		// setInterval(() => {
		// 	let list = Array.from({ length: 60 }, () => {
		// 		return (Math.random() * 2 - 1).toFixed(4); // 保留4位小数
		// 		return 0;
		// 	});
		// 	let ecgArr = [...this.ecgArr];
		// 	ecgArr = ecgArr.concat(list);
		// 	this.ecgArr = ecgArr.slice(-3000);
		// }, 40);
	},
	onUnload() {
		// 不在当前页面的时候断开连接
		this.disconnectToDevice();
		// 关闭实时指令timer
		this.stopRealTimeEcg();
		//如果还在查找设备，先停止查找
		if (foundTimer || this.deviceStatus == 0) {
			this.clearfoundTimer();
		}
	},
	methods: {
		// 搜索周围设备
		devicesDiscovery() {
			this.isConnected = false;
			this.connectedDevice = null;
			this.deviceStatus = 0;
			ER.startDevicesDiscovery();
			//5s没有找到设备，就提示没有发现设备
			if (foundTimer) {
				clearTimeout(foundTimer);
			}
			foundTimer = setTimeout(() => {
				this.clearfoundTimer();
			}, 10000);
		},
		// 连接指定设备
		connectToDevice(index) {
			clearTimeout(foundTimer);
			foundTimer = null;
			this.show = false;
			ER.stopDevicesDiscovery();
			const targetDevice = this.devicesDiscovered[index];
			ER.connectToDevice(targetDevice).then(() => {
				console.log("链接成功了吗");
				if (!this.isFirst) {
					this.getRealTimeEcg();
				}
				this.setMode(this.waveMode);
				// setTimeout(() => {
				// 	this.asyncTime();
				// }, 200);
			});
		},
		// 断开当前连接设备
		disconnectToDevice() {
			ER.disconnectToDevice();
		},
		startUse() {
			this.isFirst = false;
			this.getRealTimeEcg();
			/* 如果导联正常，需要重置一下时间 */
			this.$nextTick(() => {
				if (this.deviceStatus == 2 && this.contactedStatus == "06") {
					this.reset();
				}
			});
		},
		getRealTimeEcg() {
			ER.waveDataArray = [];
			ER.allWaveData = [];
			//清除图表更新
			if (LineCIds) {
				clearInterval(LineCIds);
				LineCIds = null;
			}
			//定时更新数据心电
			LineCIds = setInterval(() => {
				//y轴数据
				let nowWave = ER.drawEcg();
				// 连续空数据计数
				//if (!this.emptyWaveCount) this.emptyWaveCount = 0;
				if (nowWave.length == 0) {
					this.emptyWaveCount++;
					if (this.emptyWaveCount < 5) {
						// 第1次空，直接跳过本次
						return;
					} else {
						// 连续5次空，才补0
						for (var i = 0; i < 40; i++) {
							nowWave.push(0);
						}
						// this.emptyWaveCount = 0;
					}
				} else {
					this.emptyWaveCount = 0;
					nowWave = nowWave.map((item) => {
						// item = item > 1 ? 1 : item < -1 ? -1 : item;
						return item / this.gain;
					});
				}
				//console.log('nowWave', nowWave)
				let ecglist = [...this.ecglist, ...nowWave];
				let nowWaveList = [];
				if (ecglist.length <= 3000) {
					this.ecglist = [...ecglist];
					nowWaveList = [...ecglist, ...this.oldecglist.slice(ecglist.length)];
					for (let i = 0; i < 50; i++) {
						nowWaveList[(ecglist.length + i + 1) % 3000] = null;
					}
				} else {
					const len1 = ecglist.length % 3000;
					let dlist = ecglist.splice(3000);
					this.ecglist = [...dlist];
					this.oldecglist = [...ecglist];
					ecglist.splice(0, len1, ...dlist);
					nowWaveList = [...ecglist];
					for (let i = 0; i < 50; i++) {
						nowWaveList[(len1 + i + 1) % 3000] = null;
					}
				}

				// console.log('nowWaveList', nowWaveList);
				this.ecgArr = nowWaveList;
				this.chartData = JSON.parse(
					JSON.stringify({
						categories,
						series: [
							{
								name: "心电图",
								data: nowWaveList
							}
						]
					})
				);
			}, 40);
		},
		// 停止实时监听
		stopRealTimeEcg() {
			console.log("到这里了吗");
			//关闭计时
			this.clear();
			//清除图表更新
			if (LineCIds) {
				clearInterval(LineCIds);
				LineCIds = null;
			}
			//清除定时保存
			console.log("saveTimer", saveTimer);
			if (!!saveTimer) {
				clearInterval(saveTimer);
				saveTimer = null;
				console.log("清除成功了");
			}
		},
		retry() {
			this.deviceStatus = 0;
			this.devicesDiscovery();
		},

		timing(second) {
			//实时返回计时时间
			// console.log(second);
		},
		reset() {
			//重置计时器
			this.$refs.timer.reset();
			//生成新的批次号
			batchId = this.$u.guid(20);
			packNum = 0;
		},
		start() {
			//手动开启计时器
			this.$refs.timer.start();
		},
		clear() {
			//停止计时器
			this.$refs.timer && this.$refs.timer.clear();
		},
		clearfoundTimer() {
			console.log("到定时器结束了吗");
			ER.stopDevicesDiscovery();
			clearTimeout(foundTimer);
			foundTimer = null;
			this.stopRealTimeEcg();
			if (this.show) {
				// this.deviceStatus = 1;
			} else {
				this.deviceStatus = 3;
			}
		},
		close() {
			this.show = false;
		},
		//清除设备历史数据
		clearData() {
			//清除之前需要关闭离线测量
			this.setOfflinerec(0);
			setTimeout(() => {
				let str = "                   ";
				ER.writeValue(str);
			}, 400);
			setTimeout(() => {
				ER.writeValue("fileclean 1");
			}, 500);
			uni.showToast({
				title: "开始清除，请耐心等待",
				icon: "none"
			});
		},
		changeMode() {
			console.log("this.waveMode", this.waveMode);
			this.setMode(this.waveMode);
		},
		changeSaveMode() {
			// this.setSaveMode(this.saveWaveMode);
		},
		/* 心电幅度 */
		setMode(type) {
			let str = "                   ";
			ER.writeValue(str);
			setTimeout(() => {
				str = "setECGmode " + type;
				ER.writeValue(str);
			}, 200);
		},
		setSaveMode(type) {
			let str = "                   ";
			ER.writeValue(str);
			setTimeout(() => {
				str = "flashmode " + type;
				ER.writeValue(str);
			}, 100);
		},
		/* 离线测量 */
		setOfflinerec(type) {
			if (type == 1) {
				//先设置存储模式
				this.setSaveMode(this.saveWaveMode);
				//离线测量先同步时间
				setTimeout(() => {
					this.asyncTime();
				}, 200);
			}
			setTimeout(
				() => {
					let str = "                   ";
					ER.writeValue(str);
				},
				type == 1 ? 400 : 200
			);
			setTimeout(
				() => {
					ER.writeValue("offlinerec " + type);
				},
				type == 1 ? 500 : 300
			);
		},
		/* 同步时间 */
		asyncTime() {
			let str = "                   ";
			ER.writeValue(str);
			let time = new Date().getTime();
			console.log("sendTime", "time " + time);
			setTimeout(() => {
				str = "time " + time;
				ER.writeValue(str);
			}, 100);
		},
		resetdevicesDiscovery() {
			this.batteryValue = null;
			this.bpmData = null;
			this.deviceMac = "";
			this.disconnectToDevice();
			setTimeout(() => {
				this.retry();
			}, 800);
		},
		//设备重连
		reconnectToDevice() {
			//this.deviceStatus = 1;
			if (!!this.deviceMac) {
				if (this.reconnectCount < this.maxReconnect) {
					this.reconnectCount++;
					console.log("重连" + this.reconnectCount);
					ER.reconnectToDevice(this.connectedDevice)
						.then(() => {
							ER.connectionState = true;
							this.deviceStatus = 2;
							this.reconnectCount = 0; // 重置计数
						})
						.catch(() => {
							if (this.reconnectCount >= this.maxReconnect) {
								ER.foundDevices = [];
								this.isConnected = false;
								this.connectedDevice = null;
								this.batteryValue = null;
								this.bpmData = null;
								ER.contactedStatus = ""; //把导联状态置空
								this.contactedStatus = "01";
								this.clear();
								this.reconnectCount = 0; // 重置计数
								this.deviceStatus = 3;
							} else {
								setTimeout(() => {
									this.reconnectToDevice(); // 递归模拟再次断开，继续重连
								}, 1000);
							}
						});
				}
			} else {
				ER.foundDevices = [];
				this.isConnected = false;
				this.connectedDevice = null;
				this.batteryValue = null;
				this.bpmData = null;
				ER.contactedStatus = ""; //把导联状态置空
				this.contactedStatus = "01";
				this.clear();
				this.reconnectCount = 0; // 重置计数
				this.deviceStatus = 3;
			}
		},
		//确认操作
		confirm() {
			if (this.confirmType == "stop") {
				this.setOfflinerec(0);
			} else if (this.confirmType == "start") {
				this.setOfflinerec(1);
			} else {
				this.clearData();
			}
			this.confirmShow = false;
		},
		handleComfirm(confirmType) {
			this.confirmType = confirmType;
			this.confirmShow = true;
		}
	}
};
</script>

<style scoped lang="scss">
.pageview {
	background: #f2f2f2;
	height: 100vh;
	::v-deep .uni-select {
		font-size: 24rpx;
	}
}

.toptip {
	background: #fff;
	padding: 0 20upx;
	height: 60rpx;
	// position: absolute;
	// top: 0;
	// left: 0;
	// right: 0;

	.btn {
		background: $u-primary;
		padding: 0 20upx;
		color: #fff;
		border-radius: 50upx;
		line-height: 60upx;
	}
}

.toolbar {
	background: #fff;
	padding: 20upx;
}

.charts {
	width: 100%;
	height: 720upx;
	background: #fff;
	margin-top: 30upx;
	padding: 10upx 0;
	box-sizing: border-box;
	position: relative;
	&.hideCanvas {
		position: fixed;
		top: 99999px;
		left: 99999px;
	}
}
.start-icon {
	position: absolute;
	top: 60rpx;
	left: 3em;
	display: flex;
	font-size: 10px;
	.line1,
	.line3 {
		width: 15rpx;
		height: 30rpx;
		border-bottom: 2px solid #050006;
	}
	.line2 {
		width: 30rpx;
		height: 30rpx;
		border: 2px solid #050006;
		border-bottom: none;
	}
}
.bpm {
	position: absolute;
	right: 30upx;
	top: 50upx;

	.num {
		font-size: 60upx;
		font-weight: 600;
	}
}

.charts-box {
	width: 100%;
	height: 650upx;

	// border: 1px solid #f00;
	&.linechartsCopy {
		width: auto;
		position: absolute;
		left: 20upx;
		right: 20upx;
		top: 20upx;
	}
}

.popup {
	padding: 30rpx;
	background: #f2f2f2;
	width: 80vw;
	border-radius: 10px;

	.popup-hd {
		font-size: 30rpx;
		margin-bottom: 30rpx;
	}

	.popup-bd {
		max-height: 60vh;
		overflow: auto;
	}

	.device {
		background: #fff;
		padding: 20upx 30upx;
		border-radius: 12rpx;
		color: #666;

		& + .device {
			margin-top: 20rpx;
		}

		.name {
			color: #333;
			font-size: 30upx;
			margin-bottom: 10upx;
		}
	}
}

.blueState {
	// position: absolute;
	// left: 0;
	// top: 140upx;

	//top: 160upx;
	image {
		width: 60upx;
		height: 60upx;
		margin: 0 auto;
	}

	.name {
		color: #999;
		margin-top: 10upx;
		font-size: 30upx;

		&.active {
			color: #36b7ab;
		}
	}
}

.electricityState {
	// position: absolute;
	// right: 0;
	// top: 160upx;

	image {
		width: 60upx;
		height: 60upx;
	}

	.battery-container {
		--battery-level: 15%;
		display: inline-block;
		position: relative;
		/* width: 60px;
		  height: 30px; */
		width: 40px;
		height: 20px;
		border: 2px solid #333;
		border-radius: 3px;
		background: #f5f5f5;
		margin-right: 5px;
		transform: rotate(-90deg);
	}

	.battery-head {
		position: absolute;
		right: -6px;
		//top: 7px;
		top: 2px;
		width: 4px;
		height: 12px;
		background: #333;
		border-radius: 0 2px 2px 0;
	}

	.battery-level {
		position: absolute;
		left: 2px;
		top: 2px;
		bottom: 2px;
		width: var(--battery-level);
		//background: var(--battery-color, #4CAF50);
		background: #4caf50;
		border-radius: 1px;
	}

	.battery-percent {
		display: inline-block;
		font-family: Arial, sans-serif;
		font-size: 14px;
		vertical-align: middle;
		color: #333;
		font-weight: bold;
		margin-top: 12px;
		text-align: center;
	}

	.low-battery {
		color: #ff4444;
	}

	/* 低电量样式 */
	.battery-container .battery-level {
		animation: pulse 1.5s infinite;

		&.low-battery {
			background: #ff4444;
		}
	}
}

.footerbar {
	background: #fff;
	padding: 30upx 20rpx;
	padding-bottom: calc(60upx + env(safe-area-inset-bottom) / 2);
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
}
</style>
<style>
@keyframes pulse {
	0% {
		opacity: 1;
	}

	50% {
		opacity: 0.6;
	}

	100% {
		opacity: 1;
	}
}
</style>
